package cn.com.homeyoda.aimate.aihealth.ui.record.blood_pressure;

import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.FACE_ID;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartModel;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartView;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AASeriesElement;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartLineDashStyleType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartType;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAChart;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AALabels;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAMarker;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAOptions;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPlotLinesElement;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStyle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATitle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAXAxis;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAYAxis;
import com.github.AAChartModel.AAChartCore.AATools.AAGradientColor;
import com.github.AAChartModel.AAChartCore.AATools.AALinearGradientDirection;
import com.google.android.material.datepicker.MaterialDatePicker;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseFragment;
import cn.com.homeyoda.aimate.aihealth.bean.BloodPressureBean;
import cn.com.homeyoda.aimate.aihealth.databinding.FragmentBloodPressureRecordBinding;
import cn.com.homeyoda.aimate.aihealth.ui.my.family.FamilyViewModel;
import cn.com.homeyoda.aimate.aihealth.utils.DateFormatUtil;

/**
 * 血压记录
 */
public class BloodPressureRecordFragment extends BaseFragment<FragmentBloodPressureRecordBinding, FamilyViewModel> {

    private String faceId;
    private int currentIndex = 10;
    private BloodPressureRecordAdapter bloodPressureRecordAdapter;
    Date currentDate = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat dateDayFormat = new SimpleDateFormat("yyyy-MM-dd");
    private String startTime = "2025-04-10 00:00:00";
    private String endTime = dateFormat.format(currentDate);

    public static BloodPressureRecordFragment newInstance(String faceId) {
        BloodPressureRecordFragment fragment = new BloodPressureRecordFragment();
        Bundle args = new Bundle();
        args.putString(FACE_ID, faceId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public FamilyViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(FamilyViewModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        if (getArguments() != null) {
            faceId = getArguments().getString(FACE_ID);
            updateFaceId(faceId);
        }
        initView();
    }

    public void updateFaceId(String faceId) {
        if (TextUtils.isEmpty(faceId)) return;
        this.faceId = faceId;

        viewModel.getBloodPressureRecord(faceId, startTime, endTime, 10);
//        viewModel.getBloodPressureRecord(faceId, "", "", 10);
    }

    private void initView() {
        binding.btnTen.setChecked(true);
        binding.cardDatePicker.setOnClickListener(v -> showTimedialog());
        binding.btnTen.setOnClickListener(v -> setBtnChecked(10));
        binding.btnThirty.setOnClickListener(v -> setBtnChecked(30));
        binding.btnNinety.setOnClickListener(v -> setBtnChecked(90));
        binding.tvTimePeriod.setText("2025-04-10"+"至"+dateDayFormat.format(currentDate));
        initRecyclerView();
    }

    private void showTimedialog(){
        // 定义日期选择器
        MaterialDatePicker<Pair<Long, Long>> datePicker = MaterialDatePicker.Builder.dateRangePicker()
                .setTitleText("选择日期范围")
                .setSelection(Pair.create(MaterialDatePicker.todayInUtcMilliseconds(),
                        MaterialDatePicker.todayInUtcMilliseconds()))
                .build();

        // 显示选择器
        datePicker.show(getFragmentManager(), "DATE_PICKER");

        // 处理选择结果
        datePicker.addOnPositiveButtonClickListener(selection -> {
            Long startDate = selection.first;
            Long endDate = selection.second;

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String dateRange = sdf.format(new Date(startDate)) + "至" +
                    sdf.format(new Date(endDate));
            startTime = sdf.format(new Date(startDate))+" 00:00:00";
            endTime = sdf.format(new Date(endDate))+" 23:59:59";
            binding.tvTimePeriod.setText(dateRange);
            setBtnChecked(currentIndex);
            Log.i("huage","textString===="+dateRange);
        });
    }

    private void setBtnChecked(int days) {
        binding.btnTen.setChecked(days == 10);
        binding.btnThirty.setChecked(days == 30);
        binding.btnNinety.setChecked(days == 90);
//        if (currentIndex == days) return;
        currentIndex = days;
//        viewModel.getBloodPressureRecord(faceId, "", "", days);
        viewModel.getBloodPressureRecord(faceId, startTime, endTime, days);
    }

    private void initRecyclerView() {
        bloodPressureRecordAdapter = new BloodPressureRecordAdapter(R.layout.blood_pressure_record_item);
        binding.setLayoutManager(new LinearLayoutManager(getActivity()));
        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.divider_transparent_2));
        binding.rvPhysicalExam.addItemDecoration(divider);
        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.blood_pressure_record_header, null);
        View footerView = LayoutInflater.from(getContext()).inflate(R.layout.blood_pressure_record_footer, null);
        bloodPressureRecordAdapter.addHeaderView(headerView);
        bloodPressureRecordAdapter.addFooterView(footerView);
        binding.setAdapter(bloodPressureRecordAdapter);
    }

    private void aaChartView(List<BloodPressureBean.DataBean> dataList) {

        int diastolicMaxValue = 0;
        int diastolicMinValue = 0;
        int systolicMaxValue = 0;
        int systolicMinValue = 0;
        List<String> dateList = new ArrayList<>();
        List<Integer> systolicList = new ArrayList<>();
        List<Integer> diastolicList = new ArrayList<>();
        for (BloodPressureBean.DataBean visualData : dataList) {
            if (diastolicMaxValue == 0 || diastolicMinValue == 0) {
                diastolicMaxValue = visualData.getDiastolicValueMax();
                diastolicMinValue = visualData.getDiastolicValueMin();
            }
            if (systolicMaxValue == 0 || systolicMinValue == 0) {
                systolicMaxValue = visualData.getSystolicValueMax();
                systolicMinValue = visualData.getSystolicValueMin();
            }
            dateList.add(DateFormatUtil.formatToMMDD(visualData.getAddTime()));
            systolicList.add(visualData.getSystolicPressure());
            diastolicList.add(visualData.getDiastolicPressure());
        }

        binding.aaChartContainer.removeAllViews();
        AAChartView aaChartView = new AAChartView(getContext());
        binding.aaChartContainer.addView(aaChartView);
        aaChartView.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.divider_transparent));
        aaChartView.setIsClearBackgroundColor(true);

        Object[][] blueStopsArr = new Object[][]{
                {0.0, "#00BFFF00"},
                {0.5, "#00BFFF00"},
                {1.0, "#00BFFF1A"},
        };

        Map<String, Object> gradientBlueColorDic = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToTop,
                blueStopsArr
        );

        Object[][] redStopsArr = new Object[][]{
                {0.0, "#FF8C0000"},
                {0.5, "#FF8C0000"},
                {1.0, "#FF8C001A"},
        };

        Map<String, Object> gradientRedColorDic = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToTop,
                redStopsArr
        );

        // 配置 AAChartModel
        AAChartModel aaChartModel = new AAChartModel()
                .chartType(AAChartType.Areaspline)
                .title("")
                .dataLabelsEnabled(false)
                .markerRadius(0)
                .yAxisTitle("")
                .legendEnabled(false)
                .yAxisGridLineWidth(0f)
                .tooltipEnabled(false)
                .dataLabelsStyle(new AAStyle().color("#000000CC").fontSize(20f))
                .series(new AASeriesElement[]{
                        new AASeriesElement()
                                .name("收缩压")
                                .color("#00BFFF")
                                .lineWidth(2f)
                                .fillColor(gradientBlueColorDic)
                                .fillOpacity(0.5f)
                                .data(diastolicList.toArray(new Integer[0]))
                                .enableMouseTracking(false) // 禁用鼠标跟踪
                                .showInLegend(false)        // 不在 legend 中显示
                                .marker(new AAMarker().enabled(false)) // 不显示 marker 点
                        ,

                        new AASeriesElement()
                                .name("舒张压")
                                .color("#FF8C00")
                                .lineWidth(2f)
                                .fillColor(gradientRedColorDic)
                                .data(systolicList.toArray(new Integer[0]))
                                .enableMouseTracking(false) // 禁用鼠标跟踪
                                .showInLegend(false)        // 不在 legend 中显示
                                .marker(new AAMarker().enabled(false)) // 不显示 marker 点
                });

        // 设置辅助线
        AAOptions aaOptions = aaChartModel.aa_toAAOptions();
        aaOptions.chart(new AAChart().type(aaChartModel.chartType).marginTop(20));
        aaOptions.xAxis(new AAXAxis()
                        .tickInterval(3)
                        .categories(dateList.toArray(new String[0]))
                        .labels(new AALabels()
                                .style(new AAStyle()
                                        .color("#000000CC")
                                        .fontSize(20f)
                                )
                                .x(20f)
                                .y(40f)
                        )
                )
                .yAxis(new AAYAxis()
                        .min(0)
                        .max(150)
                        .labels(new AALabels()
                                .style(new AAStyle()
                                        .color("#00000066")
                                        .fontSize(18f)
                                        .textAlign("right")
                                )
                                .x(5f)
                                .y(-2f)
                        )
                        .tickInterval(30)
                        .offset(10f)
                        .gridLineColor("#6C7B8A1A")
                        .gridLineWidth(1f)
                        .title(new AATitle().text(""))
                        .plotLines(new AAPlotLinesElement[]{
                                new AAPlotLinesElement().color("#FF3333").dashStyle(AAChartLineDashStyleType.ShortDash).value(systolicMaxValue).width(2f),
                                new AAPlotLinesElement().color("#FF3A79").dashStyle(AAChartLineDashStyleType.ShortDash).value(systolicMinValue).width(2f),
                                new AAPlotLinesElement().color("#5ECFAC").dashStyle(AAChartLineDashStyleType.ShortDash).value(diastolicMaxValue).width(2f),
                                new AAPlotLinesElement().color("#0065FF").dashStyle(AAChartLineDashStyleType.ShortDash).value(diastolicMinValue).width(2f),
                        }));

        // 渲染图表
        aaChartView.aa_drawChartWithChartOptions(aaOptions);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.bloodPressureData.observe(this, list -> {
            bloodPressureRecordAdapter.setNewData(list);
            aaChartView(list);
        });
    }


    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_blood_pressure_record;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
